<template>
  <div class="home">
    <CommonHeader title="首页" />

    <!-- search + tabs切换 -->
    <div class="home-nav">
      <!-- search -->
      <div class="search">
        <Icon name="position" size="20px" color="#fff" v-if="!locationprive" @click="handleLocationClick" />
        <p class="location" v-else @click="handleLocationClick"> {{ locationprive }}</p> 
        <p>严选商城</p>
        <div class="search-input">
          <Icon name="search" size="20px" color="#ff6140" />
          <input type="text" placeholder="请搜索关键词" v-model="searchKey" @focus="handleSearch" />
        </div>
        <Icon name="shangcheng" size="24px" color="#fff" />
      </div>

      <!-- tabs -->
      <div class="tabs-container">
        <div class="tabs">
          <div v-for="(tab, index) in tabs" :key="tab.id" class="tab-item" @click="goProductList(index, tab.id)"
            ref="tabItems">
            <p>{{ tab.catename }}</p>
          </div>

          <!-- 下划线 -->
          <div class="underline" :style="{
            width: underlineWidth + 'px',
            left: underlineLeft + 'px',
          }"></div>
        </div>
        <!-- 分类 -->
        <div class="fenlei">
          <Icon name="fenlei" size="22px" color="#fff" />
          <p>分类</p>
        </div>
      </div>
    </div>
    <Carousel :bannersList="banners"></Carousel>
    <!-- 功能导航区 -->
    <div class="function-nav">
      <div class="function-nav-item" v-for="(item, index) in functionNav" :key="index">
        <img :src="item.img" alt="" />
        <p>{{ item.name }}</p>
      </div>
    </div>
    <!-- seckill 秒杀区 -->
    <div class="seckill">
      <div class="leftseckill">
        <div class="title">
          <span>限时秒杀</span>
          <span>
            查看更多
            <Icon name="youjiantou" size="8px" color="#ff6140" />
          </span>
        </div>
        <div class="left_seckill_info">
          <div class="van-count-down">
            <span class="block">0</span><span class="colon">:</span><span class="block">0</span><span
              class="colon">:</span><span class="block">0</span>
          </div>
        </div>
        <img mode="widthFix" class="seckill_img" />
      </div>
      <div class="rightseckill">
        <div class="top">
          <div>品牌上新</div>
          <div>9点整,抢大牌</div>
          <div>疯抢红包 &gt;</div>
        </div>
        <div class="bottom">
          <div>日用好物</div>
          <div>愿君多采撷</div>
          <div>塞满奖券 &gt;</div>
        </div>
      </div>
    </div>
    <!-- 推荐区 -->
    <div class="recommend">
      <div class="recommend-title">
        <span class="tuijian_active">双十一尖货预购</span>
        <span>畅购全球</span>
      </div>
      <div class="tuijian_scroll_x">
        <div class="tuijian_scroll_x_row">
          <img src="/static/img/01img.png" />
        </div>
        <div class="tuijian_scroll_x_row">
          <img src="/static/img/02img.png" />
        </div>
        <div class="tuijian_scroll_x_row">
          <img src="/static/img/03img.png" />
        </div>
        <div class="tuijian_scroll_x_row">
          <img src="/static/img/04img.png" />
        </div>
        <div class="tuijian_scroll_x_row">
          <img src="/static/img/05img.png" />
        </div>
      </div>
    </div>
    <!-- tabs-card区 -->
    <div class="tabs-card">
      <div class="tabs-wrap">
        <div class="tabs">
          <div v-for="(tab, index) in tabsCard" :key="index" :class="['tab', { active: activeIndex === index }]"
            @click="activeIndex = index">
            <span>{{ tab.label }}</span>
          </div>
        </div>
      </div>
      <div class="tabs-card-content">
        <div class="tab-pane" v-for="tab in tabsData" v-show="activeIndex === tab.index" :key="tab.index">
          <div class="van-card" v-for="item in tab.items" :key="item.id">
            <SwipeCell :title="item.goodsname" :price="item.price">
              <template #left-title>
                {{ tab.title }}
              </template>
              <template #left-image>
                <CustomImage :src="'http://43.138.15.137:4000/' + item.img"></CustomImage>
              </template>
              <template #quantity>
                <div class="van-button__content">
                  <button class="van-button__text">立即抢购</button>
                </div>
              </template>
            </SwipeCell>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CommonHeader from '@/components/common/publicHeader/index.vue';

import Icon from '@/components/common/Icon/index.vue';
import Carousel from '@/components/common/carousel/index.vue';
import { getTabsAPI, getbannerAPI, gethortgoodsAPI } from '@/api/home';
import SwipeCell from '@/components/common/swipeCell/index.vue';
import CustomImage from '@/components/common/Image/index.vue';
import axios from 'axios';
export default {
  name: 'home',
  components: {
    CommonHeader,
    Icon,
    Carousel,
    SwipeCell,
    CustomImage,
  },
  data() {
    return {
      // 定位信息
      locationprive: '',
      imageList: [
        'http://43.138.15.137:4000//uploads/3e475a60-8737-11f0-9b43-53be8531636c.png',
        'http://43.138.15.137:4000//uploads/305b6d50-8710-11f0-9b43-53be8531636c.jpg',
        'http://43.138.15.137:4000//uploads/fc926180-8715-11f0-9b43-53be8531636c.jpg',
      ],
      // 搜索关键词
      searchKey: '',

      tabs: [],
      underlineWidth: 0,
      underlineLeft: 0,
      currentIndex: 0, // 当前选中的 tab 索引

      // 轮播图数据
      banners: [],

      // 功能导航数据
      functionNav: [
        {
          img: '',
          name: '限时秒杀',
        },
        {
          img: '',
          name: ' 畅销商品',
        },
        {
          img: '',
          name: '品质大牌',
        },
        {
          img: '',
          name: '商城自营',
        },
        {
          img: '',
          name: '积分商城',
        },
      ],
      activeIndex: 0, // 默认第一个高亮
      tabsCard: [
        { label: '热门推荐' },
        { label: '上心推荐' },
        { label: '所有商品' },
      ],
      hotgoods: [],
    };
  },
  mounted() {
    // 初始化banner
    this.getbanner();
    // 初始化tabs
    this.getTabs();
    // 请求热门商品
    this.gethortgoods();
    // ✅ 添加 resize 监听器
    window.addEventListener('resize', this.handleResize);
  },
  created() {
    // 初始化定位
    this.getgeography();
  },
  beforeDestroy() {
    // ✅ 移除事件监听器
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      // 延迟执行确保 DOM 已更新
      this.$nextTick(() => {
        this.initUnderline();
      });
    },
    //  请求tabs
    async getTabs() {
      try {
        const res = await getTabsAPI();
        const { list } = res;
        this.tabs = list;
        this.$nextTick(() => {
          this.initUnderline();
        });
      } catch (err) {
        console.log(err);
      }
    },
    // 请求banner
    async getbanner() {
      try {
        const res = await getbannerAPI();
        const { list } = res;
        this.banners = list.map(item => ({
          ...item,
          img: 'http://43.138.15.137:4000' + item.img,
        }));
      } catch (err) {
        console.error('Error fetching banners:', err);
      }
    },
    // 请求热门商品
    async gethortgoods() {
      try {
        const res = await gethortgoodsAPI();
        const { list } = res;
        this.hotgoods = list.map(category => ({
          ...category,
          content: category.content.map(item => ({
            ...item,
            imgError: false, // 添加初始状态
          })),
        }));
      } catch (err) {
        console.error('Error fetching hotgoods:', err);
      }
    },

    // 跳转商品列表
    goProductList(index, id) {
      this.currentIndex = index;
      this.setUnderline(index);
      setTimeout(() => {
        this.$router
          .push({
            path: '/productList',
            query: { id, type: 1 },
          })
          .catch(err => {
            // ✅ 捕获导航被取消的异常
            // 可以静默处理，或只打印非关键错误
            if (
              !err.message.includes('Redirected') &&
              !err.message.includes('aborted')
            ) {
              console.error('Unexpected error:', err);
            }
          });
      }, 800);
    },

    // 初始化下划线
    initUnderline() {
      this.$nextTick(() => {
        const firstTab = this.$refs.tabItems[0];
        if (!firstTab) return;
        // ✅ 获取组件内部的原生 DOM 元素
        const dom = firstTab.$el || firstTab;
        this.underlineWidth = dom.offsetWidth;
        this.underlineLeft = dom.offsetLeft;
      });
    },
    setUnderline(index) {
      this.$nextTick(() => {
        const tabItems = this.$refs.tabItems;
        if (!tabItems || !tabItems[index]) return;

        const tab = tabItems[index];
        const dom = tab.$el || tab;
        this.underlineWidth = dom.offsetWidth;
        this.underlineLeft = dom.offsetLeft;
      });
    },
    // 图片加载失败
    handleImageError(item) {
      this.$set(item, 'imgError', true); // 使用 this.$set 确保响应式
    },
    // 获焦跳转search 并传递数据
    handleSearch() {
      this.$router.push({
        path: '/search',
        query: {
          id: 3,
          type: 1,
        },
      });
    },

    //  获取
    async getgeography() {
      try {
        // 1. 使用 H5 获取用户当前经纬度
        const position = await new Promise((resolve, reject) => {
          if (!navigator.geolocation) {
            reject(new Error('您的浏览器不支持地理位置定位'));
            return;
          }

          navigator.geolocation.getCurrentPosition(
            (pos) => resolve(pos),
            (err) => reject(err),
            {
              enableHighAccuracy: true, // 高精度
              timeout: 5000,            // 超时时间
              maximumAge: 60000,        // 缓存时间
            }
          );
        });

        const { latitude, longitude } = position.coords;

        const location = `${longitude},${latitude}`; // 注意：高德是 "经度,纬度"
        // 2. 调用高德 API 进行逆地理编码
        const res = await axios.get('https://restapi.amap.com/v3/geocode/regeo', {
          params: {
            key: '95135b8ce0d8c11bebde0431fdf117b4',
            location: location,
          },
        });

        const address = res.data.regeocode.addressComponent;
        const { province, district } = address;
        // 3. 保存定位信息
        this.locationprive = `${province} ${district}`;
      } catch (err) {
        if (err.code) {
          switch (err.code) {
            case err.PERMISSION_DENIED:
              console.error('用户拒绝了地理位置请求');
              break;
            case err.POSITION_UNAVAILABLE:
              console.error('位置信息不可用');
              break;
            case err.TIMEOUT:
              console.error('获取位置超时');
              break;
            default:
              console.error('未知错误:', err);
          }
        } else {
          console.error('请求失败:', err.message);
        }
      }
    },
    // 重新获取定位信息
    async handleLocationClick() {
      await this.getgeography();

    }


  },
  computed: {
    tabsData() {
      const tabConfigs = [
        { index: 0, title: '热门推荐' },
        { index: 1, title: '上新推荐' },
        { index: 2, title: '所有商品' },
      ];

      return tabConfigs.map(config => {
        const content = this.hotgoods[config.index]?.content || [];
        const items = content.map(item => ({
          ...item,
          imgError: item.imgError ?? false, // 保证 imgError 存在
        }));

        return {
          ...config,
          items,
        };
      });
    },
    
  },
};
</script>

<style lang="scss" scoped>
.home {
  background-color: #eeeeee;
}

.home-nav {
  .search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 46px;
    background-color: #ff6140;
    color: white;
    font-size: 16px;
    padding: 0 10px;
    gap: 10px;

    .location {
      font-size: 10px;
      color: #fff;
      // 下划线
      text-decoration: underline;
      position: relative;

      // 伪元素倒三角
      &::after {
        content: '';
        position: absolute;
        right: -10px;
        top: 50%;
        width: 0;
        height: 0;
        transform: translateY(-50%);
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-top: 4px solid #fff;
      }

    }

    .search-input {
      flex: 1;
      height: 30px;
      border-radius: 4px;
      background-color: #fff;
      overflow: hidden;
      display: flex;
      align-items: center;
      padding-left: 6px;

      input {
        height: 30px;
        padding: 0 10px;
        border: none;
        outline: none;
        width: 100%;
      }
    }
  }

  .tabs-container {
    display: flex;

    .tabs {
      flex: 1;
      /* ✅ 关键：让 .tabs 自动伸缩，不占用全部空间 */
      display: flex;
      align-items: center;
      height: 46px;
      background-color: #ff6140;
      color: white;
      padding: 0 10px;
      gap: 10px;
      position: relative;
      // 超出隐藏 可以滚动
      overflow-x: auto;
      // 可以滚动
      white-space: nowrap;

      // 滚动条
      &::-webkit-scrollbar {
        display: none;
      }

      .tab-item {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        text-decoration: none;
        color: white;
        transition: color 0.3s;
      }

      // 下划线
      .underline {
        height: 4px;
        background-color: #fff;
        position: absolute;
        bottom: 6px;
        border-radius: 2px;
        transition: left 0.3s ease, width 0.3s ease;
      }
    }

    // 分类
    .fenlei {
      padding-right: 1px;
      height: 46px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      text-decoration: none;
      color: white;

      background-color: #ff6140;
      white-space: nowrap;
    }
  }
}

.banner {
  height: 180px;
  overflow: hidden;
  position: relative;

  .banner-content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    transition: transform 0.3s ease;
    user-select: none; // 禁止文本选中
    cursor: grab;

    &.dragging {
      cursor: grabbing;
    }

    .banner-item {
      height: 100%;
      width: 100%;
      flex-shrink: 0;

      img {
        height: 100%;
        width: 100%;
        object-fit: cover;
      }
    }
  }

  // 点
  .banner-dots {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    gap: 5px;

    .banner-dot {
      width: 6px;
      height: 6px;
      background-color: rgba(255, 255, 255, 0.5);
      border-radius: 50%;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .banner-dot.active {
      width: 8px;
      height: 8px;
      background-color: #fff;
    }
  }
}

.function-nav {
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 70px;
  background-color: #fff;
  color: #000;
  padding: 0 10px;
  gap: 12px;

  .function-nav-item {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    font-size: 10px;
    text-decoration: none;
    color: #000;
    gap: 6px;
    transition: color 0.3s;

    img {
      width: 24px;
      height: 24px;
    }
  }
}

.seckill {
  height: 175px;
  background-color: #f1f1f1;
  display: flex;
  margin: 10px;

  .leftseckill {
    flex: 1;
    border-right: 1 solid #f1f1f1;
    background-color: white;
    background: url(/public/static/img/homeLeft.png) no-repeat;
    background-size: cover;

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      span:nth-child(1) {
        color: #85a642;
        font-size: 14px;
        font-weight: bold;
        margin: 10px 0 10px 10px;
      }

      span:nth-child(2) {
        font-size: 8px;
        color: #555555;
        margin: 10px 10px 0 0;
      }
    }

    .left_seckill_info {
      margin-left: 10px;

      .van-count-down {
        color: #323233;
        font-size: 14px;
        line-height: 20px;

        .block {
          display: inline-block;
          width: 16px;
          color: #fff;
          font-size: 6px;
          text-align: center;
          background-color: #5d7e37;
          border-radius: 1.5px;
        }

        .colon {
          display: inline-block;
          margin: 0 2px;
          color: #ee0a24;
        }
      }
    }

    .seckill_img {
      width: 90px;
      height: 50px;
      border-radius: 100%;
      border: 1px solid #ff6040;
      margin: 25px 8px;
    }
  }

  .rightseckill {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 5px;
    overflow: hidden;

    .top,
    .bottom {
      flex: 1;
    }

    .top {
      background: url(/public/static/img/homeRightTop.png) no-repeat;
      background-size: cover;

      div:nth-child(1) {
        color: #ff6040;
        font-weight: bold;
        font-size: 14px;
        margin: 13px 0 5px 10px;
      }

      div:nth-child(2) {
        color: #ff6040;
        font-size: 8px;
        margin: 10px 0 0 10px;
      }

      div:nth-child(3) {
        font-size: 8px;
        color: white;
        margin: 5px 0 0 10px;
        background: linear-gradient(#ff6040, #ff9878);
        border-top-right-radius: 15px;
        border-bottom-right-radius: 15px;
        width: 62px;
        line-height: 20px;
        text-align: center;
      }
    }

    .bottom {
      margin-top: 5px;
      background: url(/public/static/img/homeRightBottom.png) no-repeat;
      background-size: cover;

      div:nth-child(1) {
        color: #af40ff;
        font-weight: bold;
        font-size: 13px;
        margin: 10px 0 5px 10px;
      }

      div:nth-child(2) {
        color: #af40ff;
        font-size: 7.5px;
        margin: 10px 0 0 10px;
      }

      div:nth-child(3) {
        font-size: 7.5px;
        color: white;
        margin: 5px 0 0 10px;
        background: linear-gradient(#af40ff, #ef85ff);
        border-top-right-radius: 15px;
        border-bottom-right-radius: 15px;
        width: 62px;
        line-height: 20px;
        text-align: center;
      }
    }
  }
}

.recommend {
  width: 355px;
  height: 150px;
  margin: 0 10px 6px;
  background-color: white;
  // 隐藏滚动跳
  overflow: hidden;

  .recommend-title {
    height: 43px;
    width: 100%;
    display: flex;
    align-items: center;
    color: #999999;

    span {
      flex: 1;
      text-align: center;
      font-size: 14px;

      &.tuijian_active {
        font-weight: bold;
        color: #ff6040;
        font-size: 16px;
      }
    }
  }

  .tuijian_scroll_x {
    height: 83px;
    white-space: nowrap;
    overflow-x: auto;
    margin: 0 5px 0 5px;
    overflow: scroll;
    // 隐藏浏览器默认滚动条
    -ms-overflow-style: none;
    /* IE 和 Edge */
    scrollbar-width: none;

    /* Firefox */
    &::-webkit-scrollbar {
      display: none;
    }

    /* 🔥 关键：确保内容能撑开，并允许滑动 */
    /* 使用 scroll-snap 提高体验（可选） */
    scroll-behavior: smooth;
    scroll-snap-type: x mandatory;

    /* 💡 可选：去除 inline-block 间隙的方法之一 */
    font-size: 0; // 清除 inline-block 之间的空隙

    .tuijian_scroll_x_row {
      display: inline-block;
      margin: 0 0 0 5px;

      img {
        width: 80px;
      }
    }
  }
}

@media (min-width: 768px) {
  .recommend {
    width: 100%; // 明确占满父容器
    box-sizing: border-box; // 包含 padding 计算
  }
}

.tabs-card {
  position: relative;
  margin-bottom: 80px;

  .tabs-wrap {
    height: 30px;
    overflow: hidden;

    .tabs {
      margin: 0;
      border: none;
      height: 30px;
      border-radius: 2px;
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #fff;

      .tab {
        width: 125px;
        height: 30px;
        border: none;
        font-size: 14px;
        padding: 0 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;

        &.active {
          background: #ffa500;
          color: #fff;
          font-weight: bold;
        }
      }
    }
  }

  .tabs-card-content {
    height: 100%;
    background-color: #eeeeee;

    .tab-pane {
      width: 100%;
      background-color: #eeeeee;

      .van-card {
        background-color: #fff;
        margin: 5px 0;
        position: relative;
        box-sizing: border-box;
        padding: 8px 16px;
        color: #323233;
        font-size: 12px;

        .van-card__header {
          display: flex;

          .van-card__thumb {
            position: relative;
            -webkit-box-flex: 0;
            flex: none;
            width: 88px;
            height: 88px;
            margin-right: 8px;

            .van-image {
              position: relative;
              display: inline-block;
              width: 100%;
              height: 100%;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }

              .van-image__error {
                width: 100%;
                height: 100%;
                position: absolute;
                top: 0;
                left: 0;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                color: #969799;
                font-size: 14px;
                background-color: #f7f8fa;

                .van-image__error-icon {
                  color: #dcdee0;
                  font-size: 32px;
                }
              }
            }

            .van-card__tag {
              position: absolute;
              top: 2px;
              left: 0;

              .van-tag--danger {
                background: #ff6040;

                &.van-tag--mark {
                  border-radius: 0 999px 999px 0;
                }
              }

              .van-tag {
                position: relative;
                display: inline-flex;
                align-items: center;
                padding: 0 4px;
                color: #fff;
                font-size: 12px;
                line-height: 16px;
              }
            }
          }

          .van-card__content {
            position: relative;
            display: flex;
            -webkit-box-flex: 1;
            flex: 1;
            flex-direction: column;
            justify-content: space-between;
            min-width: 0;
            min-height: 88px;

            .van-card__title {
              max-height: 32px;
              font-weight: 500;
              line-height: 16px;
              word-wrap: break-word;

              &.van-multi-ellipsis--l2 {
                display: -webkit-box;
                overflow: hidden;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }
            }

            .van-card__bottom {
              line-height: 20px;

              .van-card__price {
                display: inline-block;
                color: #323233;
                font-weight: 500;
                font-size: 12px;

                .van-card__price-integer {
                  font-size: 0.42667rem;
                  font-family: Avenir-Heavy, PingFang SC, Helvetica Neue, Arial,
                    sans-serif;
                }
              }

              .van-card__origin-price {
                display: inline-block;
                margin-left: 5px;
                color: #969799;
                font-size: 10px;
                text-decoration: line-through;
              }

              .van-card__num {
                float: right;
                color: #969799;

                .van-button--small {
                  height: 32px;
                  padding: 0 8px;
                  font-size: 12px;

                  .van-button--info {
                    border: 1px solid #1989fa;
                  }
                }
              }
            }
          }
        }
      }
    }

    .van-button__content {
      background-color: #ff6140;
      border-color: rgb(255, 96, 64);
      border-radius: 4px;
      padding: 0 12px;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
      font-weight: bold;
      border: 0;

      .van-button__text {
        width: 100%;
        height: 100%;
        background-color: transparent;
        color: #fff;
      }
    }
  }
}
</style>
